package com.demo.baseutils.base

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.net.Uri
import android.os.Build
import android.os.PowerManager
import android.provider.Settings
import android.util.Log
import androidx.annotation.RequiresApi
import com.demo.baseutils.R
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.impl.LoadingPopupView

/**
 * @author y
 * @date 2020/8/21.
 * email：theyangchoi@163.com
 * description：基类方法-->获取一些基础的配置参数
 */
object BaseUtils {
    /**
     * 加载弹窗
     * */
    private var loadingDialog: LoadingPopupView? = null
    /**
     * 显示加载弹窗
     * */
    fun showLoadingDialog(title: String? = null,context: Context){
        if (loadingDialog == null)
            loadingDialog = XPopup.Builder(context).asLoading()

        loadingDialog?.setTitle(title)?.show()
    }

    /**
     * 关闭加载弹窗
     * */
    fun closeLoadingDialog(){
        if (loadingDialog != null)
            loadingDialog?.dismiss()
    }
    /**
     * 获取当前版本号
     * */
    fun getVersionCode(context: Context): Int {
        val packageManager: PackageManager = context.packageManager
        try {
            val packageInfo: PackageInfo = packageManager.getPackageInfo(context.packageName, 0)
            return packageInfo.versionCode
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
        }
        return 0
    }
    /**
     * 获取当前版本名称
     * */
    fun getVersionName(context: Context): String?{
        return try {
            val pi = context.packageManager.getPackageInfo(context.packageName, 0)
            pi.versionName
        } catch (e: PackageManager.NameNotFoundException) {
            e.printStackTrace()
            context.getString(R.string.null_version_name)
        }
    }
    /**
     * 判断手机厂商
     * */
    fun checkPhoneFirm():String{
        val phoneState = Build.BRAND.toLowerCase() //获取手机厂商
        if (phoneState.equals("huawei") || phoneState.equals("honor")){
            return BaseConstants.IS_HUAWEI
        }else if (phoneState.equals("xiaomi") && Build.BRAND != null){
            return BaseConstants.IS_XIAOMI
        }else if (phoneState.equals("oppo") && Build.BRAND != null){
            return BaseConstants.IS_OPPO
        }else if (phoneState.equals("vivo") && Build.BRAND != null){
            return BaseConstants.IS_VIVO
        }else if (phoneState.equals("meizu") && Build.BRAND != null){
            return BaseConstants.IS_MEIZU
        }else if (phoneState.equals("samsung") && Build.BRAND != null){
            return BaseConstants.IS_SAMSUNG
        }else if (phoneState.equals("letv") && Build.BRAND != null){
            return BaseConstants.IS_LETV
        }else if (phoneState.equals("smartisan") && Build.BRAND != null){
            return BaseConstants.IS_SMARTISAN
        }
        return ""
    }
    /**
     * 判断是否在白名单当中
     * */
    @RequiresApi(Build.VERSION_CODES.M)
    fun isIgnoringBatteryOptimizations(context: Context):Boolean{
        var isIgnoring:Boolean = false
        var powerManager: PowerManager = context.getSystemService(Context.POWER_SERVICE) as PowerManager

        if (powerManager != null){
            isIgnoring = powerManager.isIgnoringBatteryOptimizations(context.packageName)
        }
        return isIgnoring
    }
    /**
     * 申请加入白名单代码  弹框操作
     * */
    fun requestIgnoreBatteryOptimizations(context: Context){
        try {
            val intent = Intent(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS)
            intent.data = Uri.parse("package:" + context.packageName)
            context.startActivity(intent)
        }catch (e:Exception){
            e.printStackTrace()
        }
    }
    /**
     * 跳转到指定应用的首页
     */
    fun showActivity(packageName:String,context: Context){
        val intent = context.packageManager.getLaunchIntentForPackage(packageName)
        context.startActivity(intent)
    }
    fun showActivity(packageName:String,activityDir:String,context: Context){
        val intent = Intent()
        intent.component = ComponentName(packageName, activityDir)
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        context.startActivity(intent)
    }
    /**
     * 前往白名单设置管理
     * */
    fun gotoWhiteListSetting(context: Context){
        if (checkPhoneFirm().equals(BaseConstants.IS_HUAWEI)){
            try {
                showActivity(
                    "com.huawei.systemmanager",
                    "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity", context
                )
            }catch (e:Exception){
                showActivity(
                    "com.huawei.systemmanager",
                    "com.huawei.systemmanager.optimize.bootstart.BootStartActivity", context
                )
            }
        }else if (checkPhoneFirm().equals(BaseConstants.IS_XIAOMI)){
            showActivity(
                "com.miui.securitycenter",
                "com.miui.permcenter.autostart.AutoStartManagementActivity", context
            )
        }else if (checkPhoneFirm().equals(BaseConstants.IS_OPPO)){
            //oppo:操作步骤：权限隐私 -> 自启动管理 -> 允许应用自启动
            try {
                showActivity(
                    "com.coloros.phonemanager",
                    context
                )
            } catch (e1: java.lang.Exception) {
                try {
                    showActivity(
                        "com.oppo.safe",
                        context
                    )
                } catch (e2: java.lang.Exception) {
                    try {
                        showActivity(
                            "com.coloros.oppoguardelf",
                            context
                        )
                    } catch (e3: java.lang.Exception) {
                        showActivity(
                            "com.coloros.safecenter",
                            context
                        )
                    }
                }
            }
        }else if (checkPhoneFirm().equals(BaseConstants.IS_VIVO)){
            //vivo:操作步骤：权限管理 -> 自启动 -> 允许应用自启动
            showActivity(
                "com.iqoo.secure",
                context
            )
        }else if (checkPhoneFirm().equals(BaseConstants.IS_MEIZU)){
            //魅族:操作步骤：权限管理 -> 后台管理 -> 点击应用 -> 允许后台运行
            showActivity(
                "com.meizu.safe",
                context
            )
        }else if (checkPhoneFirm().equals(BaseConstants.IS_SAMSUNG)){
            //三星:操作步骤：自动运行应用程序 -> 打开应用开关 -> 电池管理 -> 未监视的应用程序 -> 添加应用
            try {
                showActivity(
                    "com.samsung.android.sm_cn",
                    context
                )
            } catch (e: java.lang.Exception) {
                showActivity(
                    "com.samsung.android.sm",
                    context
                )
            }
        }else if (checkPhoneFirm().equals(BaseConstants.IS_LETV)){
            //乐视:操作步骤：自启动管理 -> 允许应用自启动
            showActivity(
                "com.letv.android.letvsafe",
                "com.letv.android.letvsafe.AutobootManageActivity",
                context
            )
        }else if (checkPhoneFirm().equals(BaseConstants.IS_SMARTISAN)){
            //锤子:操作步骤：权限管理 -> 自启动权限管理 -> 点击应用 -> 允许被系统启动
            showActivity(
                "com.smartisanos.security",
                context
            )
        }
    }


    /**
     * 跳转到应用自启页面
     * */
    fun setAutoStartPackager(context: Context) {
        val mtype = checkPhoneFirm()
        var intent = Intent()
        Log.e("mtypeTAG","${mtype}")
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
        var componentName: ComponentName? = null
        if (mtype.equals("isXiaomi")) {
            componentName = ComponentName(
                "com.miui.securitycenter",
                "com.miui.permcenter.autostart.AutoStartManagementActivity"
            )
        } else if (mtype.equals("isHuawei")) {
            componentName = ComponentName(
                "com.huawei.systemmanager",
                "com.huawei.systemmanager.startupmgr.ui.StartupNormalAppListActivity"
            )
        } else if (mtype.equals("isVivo")) {
            componentName = ComponentName(
                "com.iqoo.secure",
                "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity"
            )
        }
        else if (mtype.equals("isOppo")) {
            componentName = ComponentName(
                "oppo com.coloros.oppoguardelf",
                "com.coloros.powermanager.fuelgaue.PowerUsageModelActivity"
            )
        }
        intent.component = componentName
        try {
            context.startActivity(intent)
        } catch (e: Exception) { //抛出异常就直接打开设置页面
            Log.e("eTAG","${e.message}")
//            intent = Intent(Settings.ACTION_SETTINGS)
//            context.startActivity(intent)
        }
    }
}